package com.youtubetv.controllers

import youtube.tv.WatchingHistory;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

class WatchingHistoryController {
  def watch = {
    UserService userService = UserServiceFactory.userService
    User user = userService.currentUser
    if(user){
	  def history = findHistory(user.email, params.id)
	  if(!history){
        history = new WatchingHistory(loginName : user.email, videoId : params.id)
	  }
	  history.lastViewed = new Date()
	  history.save()
	  render 'ok'
    }
	else{
	  render 'login failed'
	}
  }
  def skip = {
	UserService userService = UserServiceFactory.userService
	User user = userService.currentUser
	if(user){
      def history = findHistory(user.email, params.id)
	  if(history){
		long differenceInDays = (new Date().time - history.lastViewed.time) / 1000 / 60 / 60 / 24
		println "Difference in days $differenceInDays"
		render differenceInDays < 30 ? 'true' : 'false'
		return
      }
	}
    render 'false'
  }
  private WatchingHistory findHistory(def email, def videoId){
    def res = WatchingHistory.find("select wh from WatchingHistory wh where wh.loginName=:email and wh.videoId=:video", [email : email, video : videoId])
	return res
	//return res ? res[0] : null
/*	  def c = WatchingHistory.createCriteria()
	  return c.get {
			and{
			  eq('loginName', email)
			  eq('videoId', params.id)
			}
			maxResults(1)
		  }
		  */
  }
}